package id.co.rho.scoring.cid.client.utils;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;

import id.co.rho.scoring.cid.client.command.CommandDispatcherAsync;
import id.co.rho.scoring.cid.client.command.impl.LoginCommandAction;
import id.co.rho.scoring.cid.client.command.impl.LoginCommandResult;
import id.co.rho.scoring.cid.client.mvc.AppEvents;
import id.co.rho.scoring.cid.client.security.CredentialConfigurer;

import javax.inject.Inject;

public class LoginCheckImpl implements LoginCheck {

    private CommandDispatcherAsync commandDispatcherAsync;
    private CredentialConfigurer credential;
    private NavigationMenuUtils menuUtil;

    @Inject
    public LoginCheckImpl(CommandDispatcherAsync commandDispatcherAsync, CredentialConfigurer credential) {
        this.commandDispatcherAsync = commandDispatcherAsync;
        this.credential = credential;
        this.menuUtil = new NavigationMenuUtils();
    }

    @Override
    public void checkCookie() {
        String xms = Cookies.getCookie("xms");
        LoginCommandAction action = new LoginCommandAction(LoginCommandAction.TYPE.FIRSTLOAD);
        action.setStringCockie(xms);
        this.commandDispatcherAsync.execute(action, new AsyncCallback<LoginCommandResult>() {
            @Override
            public void onFailure(Throwable caught) {
            	throw new RuntimeException(caught);
            }

            @Override
            public void onSuccess(LoginCommandResult result) {
            	if (result.getCredential() == null) {
                    Dispatcher.forwardEvent(AppEvents.MainLoginView);
                } else {
                	credential.setId(result.getCredential().getId());
                	credential.setUserId(result.getCredential().getUserId());
                	credential.setUsername(result.getCredential().getUsername());
                	credential.setListRole(result.getCredential().getListRole());
//                	menuUtil.updateMenuNavigation(result.getCredential().getListRole());
//                	Registry.register("inboxCount", result.getUnreadInbox());
                    Dispatcher.forwardEvent(AppEvents.LoginSuccess);
                }
            }
        });
    }


    
}